import { HTTP } from '../../utils/http.js'
import api from '../../utils/api.js'
import { config } from '../../utils/config'
import utils from "../../utils/util"
let http = new HTTP()
var app = getApp();
let timer;

Page({

	/**
	 * 页面的初始数据
	 */
	data: {
		imgUrl: config.imgUrl,
		payBtn: true
	},

	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad: function (options) {
		let order_no = options.order;
		// let order_no = 'MC20200628628321302690860789';
		this.setData({
			order_no
		})
	},
	showView(e) {
		let index = e.currentTarget.dataset.index;
		let cookbooks = this.data.cookbooks
		cookbooks.forEach((item, key) => {
			if (key == index) {
				item.showView = !item.showView
			} else {
				item.showView = false
			}
		})
		this.setData({
			cookbooks
		})
	},
	// 获取订单详情
	getOrderDetail() {
		let that = this;
		wx.showLoading({ title: '加载中' })
		let order_no = this.data.order_no;
		http.request({
			url: api.orderDetails,
			method: 'GET',
			data: {
				order_no: order_no
			},
			success: (res) => {
				wx.hideLoading();
				let result = res.data
				if (res.code == 200) {
					that.setData(result)

					let cookbooks = this.data.cookbooks
					cookbooks.forEach(item => {
						item.showView = false
					})
					this.setData({
						cookbooks
					})
					if (result.status == 1) {
						timer = setInterval(function () {
							that.showtime()
						}, 1000);
					}


				}

			},
			fail: (res) => {

			}
		})
	},
	showtime() {
		let expire_time = this.data.expire_time
		var nowtime = new Date(); //获取当前时间
		let expireFormat = expire_time.replace(/-/g, '/');
		// console.log('expireFormat',expireFormat);
		let endtime = new Date(expireFormat);  //定义结束时间
		var lefttime = endtime.getTime() - nowtime.getTime(),  //距离结束时间的毫秒数
			leftd = Math.floor(lefttime / (1000 * 60 * 60 * 24)),  //计算天数
			lefth = Math.floor(lefttime / (1000 * 60 * 60) % 24),  //计算小时数
			leftm = Math.floor(lefttime / (1000 * 60) % 60),  //计算分钟数
			lefts = Math.floor(lefttime / 1000 % 60);  //计算秒数
		let timeOut = leftm + "分" + lefts + '秒';
		if (leftm == 0 && lefts == 0) {
			this.cancelOrderTimer();
		} else {
			this.setData({
				timeOut
			})
		}

	},
	/*申请退款*/
	refund() {

		let that = this;
		wx.showModal({
			title: '提示',
			content: '确定申请退款？',
			confirmColor: '#EA5D56',
			success(res) {
				if (res.confirm) {

					http.request({
						url: api.refundOrder,
						method: "POST",
						data: {
							order_no: that.data.order_no,
							refund_cause: '商品质量有问题'
						},
						success: (res) => {
							console.log(res);
							if (res.code == 200) {
								console.log('申请退款成功');
								that.getOrderDetail();
								clearInterval(timer);

								// 给上一页传递数据
								const pages = getCurrentPages()
								const prevPage = pages[pages.length - 2]
								prevPage.setData({
									refundOrderBack: that.data.order_no
								})

							} else {
								wx.showToast({
									icon: 'none',
									title: res.message,
								})
							}
						},
						fail: (res) => {
						}
					})

				} else if (res.cancel) {
					return;
				}
			}
		})



	},
	/*确认收货*/
	confirmReceipt() {
		let that = this
		let order_no = this.data.order_no;
		wx.showModal({
			title: '提示',
			content: '确定收货',
			confirmColor: '#EA5D56',
			success(res) {
				if (res.confirm) {

					http.request({
						url: api.userSure,
						method: "POST",
						data: {
							order_no
						},
						success: (res) => {
							console.log(res);
							if (res.code == 200) {

								// 给上一页传递数据
								const pages = getCurrentPages()
								const prevPage = pages[pages.length - 2]
								prevPage.setData({
									receiptOrderBack: order_no
								})

								that.getOrderDetail();

							}
						},
						fail: (res) => {

						}
					})


				} else if (res.cancel) {
					return;
				}
			}
		})
	},

	//删除订单
	deleteOrder() {
		let that = this;
		let order_no = that.data.order_num;
		const pages = getCurrentPages()
		const prevPage = pages[pages.length - 2] // 上一页// 调用上一个页面的setData 方法，将数据存储

		wx.showModal({
			title: '提示',
			content: '确定删除订单',
			confirmColor: '#EA5D56',
			success(res) {
				if (res.confirm) {
					prevPage.setData({
						deleteOrder: order_no
					})
					wx.navigateBack({
						delta: 1
					})
				} else if (res.cancel) {
					return;
				}
			}
		})

	},
	payOrder(e) {
		if (!this.data.payBtn) {
			return false
		} else {
			this.setData({
				payBtn: false
			})
		}
		let that = this
		let order_no = this.data.order_no;
		return new Promise((resolve, reject) => {
			http.request({
				url: api.preOrder,
				data: {
					order_no
				},
				success: res => {
					if (res.code == 200) {
						let data = res.data
						// 调起微信支付
						wx.requestPayment({
							'timeStamp': data.timeStamp,
							'nonceStr': data.nonceStr,
							'package': data.package,
							'signType': 'MD5',
							'paySign': data.paySign,
							'success': function (res) {
								console.log('支付成功', res);
								wx.setStorageSync("select-menus", '')


								// 给上一页传递数据
								const pages = getCurrentPages()
								const prevPage = pages[pages.length - 2]
								prevPage.setData({
									payOrderBack: order_no
								})



							},
							'fail': function (res) {
								that.setData({
									payBtn: true
								})
								console.log('支付失败', res);
								reject(res)

							},
							'complete': function (res) {
								that.payNotify(order_no)
							}
						})

					}
				},
				fail(res) {

				}
			})
		})
	},
	// 支付接口调用完成之后订单查询
	payNotify(order_no) {
		let that = this;
		console.log('支付回调');

		http.request({
			url: api.payNotify,
			method: "POST",
			data: {
				order_no: order_no
			},
			success: (res) => {
				console.log(res);
				if (res.code == 200) {
					// 支付成功需要修改菜篮
					that.setData({
						payBtn: true,
					})
					//支付成功更改缓存payList
					that.getOrderDetail();
				}
			},
			fail: (res) => {

			}
		})

	},

	// 取消订单
	cancelOrder() {
		let that = this;
		let order_no = that.data.order_num;
		wx.showModal({
			title: '提示',
			content: '确定取消订单',
			confirmColor: '#EA5D56',
			success(res) {
				if (res.confirm) {

					http.request({
						url: api.cancelOrder,
						method: "POST",
						data: {
							order_no
						},
						success: (res) => {
							console.log(res);
							if (res.code == 200) {
								that.getOrderDetail();
								// 给上一页传递数据
								const pages = getCurrentPages()
								const prevPage = pages[pages.length - 2]
								prevPage.setData({
									cancelOrderBack: order_no
								})

							}
						},
						fail: (res) => {

						}
					})

				} else if (res.cancel) {
					return;
				}
			}
		})

	},
	// 倒计时取消订单
	cancelOrderTimer() {
		let that = this;
		let order_no = that.data.order_num;

		http.request({
			url: api.cancelOrder,
			method: "POST",
			data: {
				order_no
			},
			success: (res) => {
				console.log(res);
				if (res.code == 200) {
					that.getOrderDetail();
					clearInterval(timer)
					// 给上一页传递数据
					const pages = getCurrentPages()
					const prevPage = pages[pages.length - 2]
					prevPage.setData({
						cancelOrderBack: order_no
					})

				}
			},
			fail: (res) => {

			}
		})

	},
	// 电话
	service(e) {
		let phone = e.currentTarget.dataset.phone;
		console.log(phone);
		wx.makePhoneCall({
			phoneNumber: phone.toString()
		})
	},
	/**
	 * 生命周期函数--监听页面初次渲染完成
	 */
	goAddComment() {
		app.globalData.shops = this.data.shops
		app.globalData.snap_items = this.data.snap_items_text;
		app.globalData.order_no = this.data.order_no;
		wx.navigateTo({
			url: '/pages/addComment/addComment'
		})
	},
	CommentList(e) {
		let shopid = e.currentTarget.dataset.shopid;
		wx.navigateTo({
			url: '/pages/comments/comments?id=' + this.data.shops.id
		})
	},
	onReady: function () {

	},

	/**
	 * 生命周期函数--监听页面显示
	 */
	onShow: function () {
		this.getOrderDetail();
	},

	/**
	 * 生命周期函数--监听页面隐藏
	 */
	onHide: function () {

	},

	/**
	 * 生命周期函数--监听页面卸载
	 */
	onUnload: function () {
		clearInterval(timer)
	},

	/**
	 * 页面相关事件处理函数--监听用户下拉动作
	 */
	onPullDownRefresh: function () {

	},

	/**
	 * 页面上拉触底事件的处理函数
	 */
	onReachBottom: function () {

	},

	/**
	 * 用户点击右上角分享
	 */
	onShareAppMessage: function () {

	}
})